package com.xudow.app.dynamicstate_old.module.discovery.viewholder;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.LayoutRes;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.tagview.TAGView;
import com.jude.utils.JUtils;
import com.squareup.picasso.Picasso;
import com.umeng.message.proguard.U;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.JTimeTransform;
import com.xudow.app.dynamicstate_old.data.DynamicModel;
import com.xudow.app.dynamicstate_old.data.ImageModel;
import com.xudow.app.dynamicstate_old.domain.Config;
import com.xudow.app.dynamicstate_old.domain.entity.Dynamic;
import com.xudow.app.dynamicstate_old.domain.entity.DynamicComment;
import com.xudow.app.dynamicstate_old.module.follow.CommentActivity;
import com.xudow.app.dynamicstate_old.module.follow.DynamicDetailActivity;
import com.xudow.app.dynamicstate_old.module.follow.ForwardActivity;
import com.xudow.app.dynamicstate_old.module.user.UserProfileActivity;
import com.xudow.app.dynamicstate_old.widget.UserClickableSpan;
import com.xudow.app.newui.PreLoginActivity;
import com.xudow.app.util.StringUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * Created by ske on 2016/5/22.
 */
public abstract class DynamicContentViewHolder extends BaseViewHolder<Dynamic> implements View.OnClickListener {
    // 每个ViewHolder的header和footer基本是一样的
    // header
    @BindView(R.id.dynamic_follows_item_avatar)
    ImageView avatar;
    @BindView(R.id.dynamic_follows_item_name)
    TextView authorName;
    @BindView(R.id.dynamic_follows_item_time)
    TextView time;
    @BindView(R.id.tag_follow)
    TAGView tagFollow;

    // footer
    @BindView(R.id.ll_thumb_up)
    View llThumbUp;
    @BindView(R.id.dynamic_follows_content_thumbup)
    ImageView thumbUpImage;
    @BindView(R.id.dynamic_follows_content_thumbup_num)
    TextView thumbUpNum;
    @BindView(R.id.dynamic_follows_content_comment_num)
    TextView commentNum;
    @BindView(R.id.dynamic_follows_content_forward_num)
    TextView forwardNum;
    @BindView(R.id.dynamic_follows_content_comments)
    LinearLayout commentsLayout;

    @BindView(R.id.ll_comment)
    View llComment;
    @BindView(R.id.ll_forward)
    View llForward;
    @BindView(R.id.image_identify)
    ImageView identify;

    RecyclerArrayAdapter<Dynamic> adapter;


    Dynamic dynamic;

    public DynamicContentViewHolder(RecyclerArrayAdapter<Dynamic> adapter, ViewGroup parent, @LayoutRes int res) {
        super(parent, res);
        this.adapter = adapter;
        ButterKnife.bind(this, itemView);
        itemView.setOnClickListener(this);
        llComment.setOnClickListener(this);
        llThumbUp.setOnClickListener(this);
        llForward.setOnClickListener(this);
        avatar.setOnClickListener(this);
        authorName.setOnClickListener(this);
        tagFollow.setOnClickListener(this);
    }


    @Override
    public void setData(Dynamic dynamic) {
        this.dynamic = dynamic;
        // 设置header
        Picasso.with(getContext()).load(ImageModel.getXueDouImage(dynamic.getHeadUrl()))
                .placeholder(R.drawable.default_head_img)
                .resize(300, 300)
                .into(avatar);

        authorName.setText(StringUtils.isEmpty(dynamic.getRemarkName()) ? dynamic.getUserName() : dynamic.getRemarkName());
        time.setText(new JTimeTransform(dynamic.getPublishTime()).toString(new JTimeTransform.RecentDateFormat("MM-dd HH:mm")));

        // 设置footer
        thumbUpNum.setText(dynamic.getLikeNum() + "");
        thumbUpImage.setImageResource(dynamic.getIsLiked() == 1 ? R.drawable.dynamic_follows_like_after : R.drawable.dynamic_follows_like);
        commentNum.setText(dynamic.getCommentNum() == 0 ? "评论" : dynamic.getCommentNum() + "");
        forwardNum.setText(dynamic.getForwardNum() == 0 ? "转发" : dynamic.getForwardNum() + "");

        if (dynamic.getIsAttended() == 1) {
            tagFollow.setText("已关注");
            tagFollow.setIcon(0);
        } else {
            tagFollow.setIcon(R.drawable.follow_plus);
            tagFollow.setText("关注");
        }

        if (dynamic.getCheckStatus() == 5) {
            identify.setVisibility(View.VISIBLE);
        } else {
            identify.setVisibility(View.GONE);
        }

        commentsLayout.removeAllViews();
        // 渲染评论列表
        List<DynamicComment> commentList = dynamic.getCommentList();
        // 对评论按照时间进行排序，以便从上到下显示
        if (commentList != null) {
            commentsLayout.setVisibility(View.VISIBLE);
            Collections.sort(commentList, new Comparator<DynamicComment>() {
                @Override
                public int compare(DynamicComment lhs, DynamicComment rhs) {
                    return (int) (rhs.getCommentTime() - lhs.getCommentTime());
                }
            });
            for (int i = 0; i < commentList.size(); i++) {
                DynamicComment comment = commentList.get(i);
                SpannableString spannableString;
                if (comment.getpId() == 0) {
                    // 没有上条评论
                    spannableString = new SpannableString(comment.getUserName() + "：" + comment.getContent());
                    spannableString.setSpan(new UserClickableSpan(getContext(), comment.getUserProfileId()), 0, comment.getUserName() == null ? 0 : comment.getUserName().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                } else {
                    // 拥有上条评论
                    spannableString = new SpannableString(comment.getUserName() + "回复" + comment.getpName() + "：" + comment.getContent());
                    spannableString.setSpan(new UserClickableSpan(getContext(), comment.getUserProfileId()), 0, comment.getUserName() == null ? 0 : comment.getUserName().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(new UserClickableSpan(getContext(), comment.getpId()), (comment.getUserName().length() + 2), (comment.getUserName().length() + comment.getpName().length()) + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                TextView textView = new TextView(getContext());
                textView.setMovementMethod(LinkMovementMethod.getInstance());
                textView.setPadding(0, JUtils.dip2px(2), 0, 0);
                textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                textView.setText(spannableString);
                commentsLayout.addView(textView);
            }
        } else {
            commentsLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_thumb_up:
                if (XApplication.getInstance().isLogin()) {
                    if (dynamic.getIsLiked() == 0)
                        DynamicModel.getInstance().like(dynamic.getId(), XApplication.getInstance().isStudent() ? 2 : 1)
                                .subscribe(message -> {
                                    dynamic.setIsLiked(1);
                                    dynamic.setLikeNum(dynamic.getLikeNum() + 1);
                                    thumbUpNum.setText(dynamic.getLikeNum() + "");
                                    thumbUpImage.setImageResource(dynamic.getIsLiked() == 1 ? R.drawable.dynamic_follows_like_after : R.drawable.dynamic_follows_like);
                                    JUtils.Toast("点赞成功");
                                });
                    else
                        DynamicModel.getInstance().unLike(dynamic.getId())
                                .subscribe(message -> {
                                    dynamic.setIsLiked(0);
                                    dynamic.setLikeNum(dynamic.getLikeNum() - 1);
                                    thumbUpNum.setText(dynamic.getLikeNum() + "");
                                    thumbUpImage.setImageResource(dynamic.getIsLiked() == 1 ? R.drawable.dynamic_follows_like_after : R.drawable.dynamic_follows_like);
                                    JUtils.Toast("已取消");
                                });
                } else {
                    getContext().startActivity(new Intent(getContext(), PreLoginActivity.class));
                }
                break;

            case R.id.tag_follow:
                if (XApplication.getInstance().isLogin()) {
                    if (XApplication.getInstance().getUserProfileId() == dynamic.getUserProfileId()) {
                        JUtils.Toast("不能关注自己");
                        return;
                    }
                    if (dynamic.getIsAttended() != 1) {
                        DynamicModel.getInstance().attention(dynamic.getUserProfileId(), dynamic.getUsertype(), XApplication.getInstance().isStudent() ? 2 : 1)
                                .subscribe(message -> {
                                    for (int i = 0; i < adapter.getCount(); i++) {
                                        Dynamic temp = adapter.getItem(i);
                                        if (temp.getUserProfileId() == dynamic.getUserProfileId())
                                            temp.setIsAttended(1);
                                    }
                                    adapter.notifyDataSetChanged();
                                    JUtils.Toast("关注成功");
                                });
                    } else {
                        DynamicModel.getInstance().unattention(dynamic.getUserProfileId())
                                .subscribe(message -> {
                                    for (int i = 0; i < adapter.getCount(); i++) {
                                        Dynamic temp = adapter.getItem(i);
                                        if (temp.getUserProfileId() == dynamic.getUserProfileId())
                                            temp.setIsAttended(0);
                                    }
                                    adapter.notifyDataSetChanged();
                                    JUtils.Toast("取消成功");
                                });
                    }
                } else {
                    getContext().startActivity(new Intent(getContext(), PreLoginActivity.class));
                }
                break;

            case R.id.dynamic_follows_item_avatar:
                Intent i = new Intent(getContext(), UserProfileActivity.class);
                i.putExtra(UserProfileActivity.USER_PROFILE_ID, dynamic.getUserProfileId());
                ((Activity) getContext()).startActivityForResult(i, Config.Code_NeedRefresh);

                break;
            case R.id.dynamic_follows_item_name:
                Intent nIntent = new Intent(getContext(), UserProfileActivity.class);
                nIntent.putExtra(UserProfileActivity.USER_PROFILE_ID, dynamic.getUserProfileId());
                ((Activity) getContext()).startActivityForResult(nIntent, Config.Code_NeedRefresh);
                break;

            case R.id.ll_comment:
                if (XApplication.getInstance().isLogin()) {
                    Intent i2 = new Intent(getContext(), CommentActivity.class);
                    i2.putExtra("dynamic", dynamic);
                    ((Activity) getContext()).startActivityForResult(i2, Config.Code_NeedRefresh);
                } else {
                    getContext().startActivity(new Intent(getContext(), PreLoginActivity.class));
                }
                break;

            case R.id.ll_forward:
                if (XApplication.getInstance().isLogin()) {
                    Intent i3 = new Intent(getContext(), ForwardActivity.class);
                    i3.putExtra("dynamic", dynamic);
                    ((Activity) getContext()).startActivityForResult(i3, Config.Code_NeedRefresh);
                } else {
                    getContext().startActivity(new Intent(getContext(), PreLoginActivity.class));
                }
                break;
            default:
                Intent intent = new Intent(getContext(), DynamicDetailActivity.class);
                intent.putExtra("dynamic", dynamic);
                ((Activity) getContext()).startActivityForResult(intent, Config.Code_NeedRefresh);
                break;

        }
    }
}
